<!-- 用户管理 -->
<template>
  <div class="app-container">

    <!-- 用户列表 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="昵称" prop="s_nickname">
          <el-input v-model="queryParams.s_nickname" placeholder="昵称" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="账号" prop="s_account">
          <el-input v-model="queryParams.s_account" placeholder="账号" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="状态" prop="usable">
          <el-select v-model="queryParams.usable" placeholder="全部" clearable class="!w-[100px]">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['sys:user:add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <el-button v-hasPerm="'sys:user:delete'" type="danger" icon="delete" :disabled="selectIds.length === 0"
            @click="handleDelete()">
            删除
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="账号id" prop="id" width="80" />
        <el-table-column label="昵称" prop="nickname" width="150" />
        <el-table-column label="登录账号" prop="account" width="150" />
        <el-table-column label="状态" align="center" prop="usable" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.usable == 1 ? 'success' : 'info'">
              {{ scope.row.usable == 1 ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="超级管理员" align="center" prop="usable">
          <template #default="scope">
            <el-tag :type="scope.row.is_root == 1 ? 'success' : 'info'">
              {{ scope.row.is_root == 1 ? "超级管理员" : "管理员" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="超级管理员" align="center" prop="usable">
          <template #default="scope">
            {{ scope.row.role_ids.join(",") }}
          </template>
        </el-table-column>


        <el-table-column label="创建时间" align="center" prop="created_at" width="180">
          <template #default="scope">
            {{ formatTimestamp(scope.row.created_at * 1000) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button v-hasPerm="'sys:user:password:reset'" type="primary" icon="RefreshLeft" size="small" link
              @click="hancleResetPassword(scope.row)">
              重置密码
            </el-button>
            <el-button v-hasPerm="'sys:user:edit'" type="primary" icon="edit" link size="small"
              @click="handleOpenDialog(scope.row)">
              编辑
            </el-button>
            <el-button v-hasPerm="'sys:user:delete'" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery" />
    </el-card>

    <!-- 用户表单 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" append-to-body @close="handleCloseDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account" :readonly="!!formData.id" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item v-if="dialog.title != '修改用户'" label="登录密码" prop="login_secret">
          <el-input v-model="formData.login_secret" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="超级管理员">
          <el-radio-group v-model="formData.is_root">
            <el-radio :value="2" label="管理员" />
            <el-radio :value="1" label="超级管理员" />
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.is_root == 2" label="角色" prop="role_ids">
          <el-select v-model="formData.role_ids" multiple placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="usable">
          <el-switch v-model="formData.usable" inline-prompt active-text="正常" inactive-text="禁用" :active-value="1"
            :inactive-value="2" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

  </div>
</template>

<script setup lang="ts">
import UserAPI, { UserForm, UserPageQuery, UserPageVO } from "@/api/system/user";
import { formatTimestamp } from '@/utils/index'
import RoleAPI from "@/api/system/role";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const queryParams = reactive<UserPageQuery>({
  page: 1,
  ps: 10,
});

const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});

const formData = reactive<UserForm>({
  usable: 1,
  is_root: 2
});

const rules = reactive({
  account: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  login_secret: [{ required: true, message: "用户密码不能为空", trigger: "blur" }],
  role_ids: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 角色下拉数据源
const roleOptions = ref<any[]>();

// 查询
function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 重置密码
function hancleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.nickname + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(
    ({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      UserAPI.resetPassword({ id: row.id, login_secret: value, login_secret_confirmation: value }).then(() => {
        ElMessage.success("密码重置成功，新密码是：" + value);
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(data?: any) {
  dialog.visible = true;

  // 加载角色下拉数据源
  let role = await RoleAPI.getPage();
  roleOptions.value = role.lists;

  if (data) {
    dialog.title = "修改用户";
    Object.assign(formData, { ...data });
    formData.role_ids = data.role_ids.map((item: number) => (Number(item)));
  } else {
    dialog.title = "新增用户";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (formData.is_root == 1) {
        formData.role_ids = [];
      }

      if (userId) {
        UserAPI.update(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.add(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  let userIds = id ? [id] : selectIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}



onMounted(() => {
  handleQuery();
});
</script>
